package cn.edu.ecut.request;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

@WebServlet( "/upload/single" )
@MultipartConfig
public class UploadSingleServlet extends HttpServlet {

    @Override
    protected void doGet( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {
        throw new RuntimeException( "不支持GET方式上传" );
    }

    @Override
    protected void doPost( HttpServletRequest request , HttpServletResponse response )
            throws ServletException, IOException {

        Part part = request.getPart( "upfile" );
        String filename = part.getSubmittedFileName();

        // 通过 请求对象 获取 当前 Servlet 对象 的 "上下文" 对象
        ServletContext sc = request.getServletContext();
        // 获取 ServletContext 初始化参数 ( 可以通过 web.xml 的 context-param 配置 )
        String store = sc.getInitParameter( "store" );

        Path target = Path.of( store , filename );
        InputStream in = part.getInputStream();
        Files.copy( in , target , StandardCopyOption.REPLACE_EXISTING );

        // 通过 状态代码 命令浏览器重新打开另一个资源
        response.setStatus( 302 ); // 设置响应状态代码
        // 通过 响应头 的 location 字段来设置 新资源的位置
        response.setHeader( "location" , "/image/show" ); // 设置 location 字段的值

        /*
        ServletContext sc = request.getServletContext();
        // String realPath = request.getRealPath( "/uploads" );
        String realPath = sc.getRealPath( "/uploads" );
        System.out.println( "path : " + realPath );

        Part part = request.getPart( "upfile" );
        System.out.println( "part : " + part );

        String filename = part.getSubmittedFileName();
        System.out.println( "filename : " + filename );
        */

        /* NIO
        InputStream in = part.getInputStream();
        Path target = Path.of( realPath , filename );
        Files.copy( in , target , StandardCopyOption.REPLACE_EXISTING );
        */

        /* IO
        InputStream in = part.getInputStream();
        OutputStream out = new FileOutputStream( realPath + "\\" + filename );

        int n ;
        byte[] bytes = new byte[ 1024 ];
        while( ( n = in.read( bytes ) ) != -1 ){
            out.write( bytes , 0 , n );
        }

        out.close();
        in.close();
        */

    }

}
